//
//  NewHomeViewController.m
//  QXShowing
//
//  Created by 王道道 on 2018/4/24.
//  Copyright © 2018年 doll_dream. All rights reserved.
//

#define kCellWidth      (App_Frame_Width-40)/2
#define kCellHeight      (kCellWidth*360)/330
#define kTopViewHeight      100
#define kCycleViewHeight      App_Frame_Width * 360/690

#import "NewHomeViewController.h"

#import "RefreshCollectionView.h"
#import "HomeCollectionViewCell.h"
#import "ShowViewController.h"
#import "HomeAddressListViewController.h"

#import "HomeShowModel.h"
#import "HomeShowListModel.h"
#import "HomeNumberModel.h"

//定位
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>

//视频播放
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>

static NSString *const cellId = @"CircleIdentify";
static NSString *const headerId = @"headerId";

@interface NewHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CollectionRefreshDelegate,UICollectionViewDelegateFlowLayout,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
@property (nonatomic, strong) RefreshCollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIButton *addressButton;
@property (nonatomic, strong) UILabel *registLabel;
@property (nonatomic, strong) UILabel *businessLabel;

@property (nonatomic, strong) UIView *playView;
@property (nonatomic, strong) AVPlayer *player;

@property (nonatomic, strong) NSString *cityName;
@property (nonatomic, strong) NSString *cityId;

@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic, strong) BMKGeoCodeSearch *geocodesearch;

@end

@implementation NewHomeViewController

#pragma mark - Lazy
- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initTopView];
    [self initPlayView];
    [self initView];
    
    //定位
    [self getCurrentAddress];
    
//    //获取首页轮播图列表
//    [self requestPostBH_Ads_getSowing];
    
    //系统游客与展商数量统计系
    [self requestPostBH_User_getSysCount];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initTopView {
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, kTopViewHeight)];
    [self.view addSubview:_topView];
    
    UILabel *showLabel = [[UILabel alloc] init];
    showLabel.font = BHFont_Size_25;
    showLabel.text = @"展馆";
    [_topView addSubview:showLabel];
    
    UILabel *detailLabel = [[UILabel alloc] init];
    detailLabel.font = BHFont_Size_11;
    detailLabel.text = @"全国展馆·展商尽在掌中";
    [_topView addSubview:detailLabel];
    
    self.registLabel = [[UILabel alloc] init];
//    self.registLabel.text = [NSString stringWithFormat:@"注册用户:%ld位", self.dataArray.count];
    self.registLabel.font = BHFont_Size_13;
    [_topView addSubview:self.registLabel];
    
    self.businessLabel = [[UILabel alloc] init];
//    self.businessLabel.text = [NSString stringWithFormat:@"注册展商:%ld位", self.dataArray.count];
    self.businessLabel.font = BHFont_Size_13;
    [_topView addSubview:self.businessLabel];
    
    _addressButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 150, 50)];//100
    [_addressButton setTitle:@"定位" forState:UIControlStateNormal];
//    [_addressButton setTitle:@"San Francisco" forState:UIControlStateNormal];
    [_addressButton setTitleColor:Text_Color_333333 forState:UIControlStateNormal];
    _addressButton.titleLabel.font = BHFont_Size_15;
//    [_addressButton setImage:[UIImage imageNamed:@"home-a-11"] forState:UIControlStateNormal];
//    CGFloat imageWidth = _addressButton.currentImage.size.width;
//    CGFloat labelWidth = [BHSettingUtil widthForText:_addressButton.titleLabel.text fontSize:15]-20;
//    [_addressButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -imageWidth, 0, imageWidth)];
//    [_addressButton setImageEdgeInsets:UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth)];
    
    [_addressButton addTarget:self action:@selector(chooseAddressAction:) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:_addressButton];
    
    UIImageView *addressIV = [[UIImageView alloc] init];
    addressIV.image = [UIImage imageNamed:@"home-a-11"];
    [_topView addSubview:addressIV];
    
    [detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_topView.mas_left).offset(20);
        make.bottom.equalTo(_topView.mas_bottom).offset(-10);
    }];
    
    [showLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(detailLabel.mas_left);
        make.bottom.equalTo(detailLabel.mas_top).offset(-10);
    }];
    
    [self.registLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(showLabel.mas_top);
        make.left.equalTo(detailLabel.mas_right).offset(15);
    }];
    
    [self.businessLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.registLabel.mas_bottom).offset(5);
        make.left.equalTo(self.registLabel.mas_left);
    }];
    
    [_addressButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_topView.mas_bottom).offset(-20);
        make.right.equalTo(_topView.mas_right).offset(-30-15);
    }];
    
    [addressIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.addressButton.mas_right).offset(0);
        make.right.equalTo(self.topView.mas_right).offset(-30);

        make.centerY.equalTo(self.addressButton.mas_centerY);
        make.width.offset(17);
        make.height.offset(15);
    }];
}

- (void)initPlayView {
    _playView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, kCycleViewHeight)];
    
    UIImageView *bgImage = [[UIImageView alloc] initWithFrame:_playView.frame];
    [bgImage sd_setImageWithURL:[NSURL URLWithString:BH_Home_pic] placeholderImage:[UIImage imageNamed:@"home-1"]];
    bgImage.userInteractionEnabled = YES;
    [_playView addSubview:bgImage];
    
    UIButton *playBtn = [[UIButton alloc] init];
    [playBtn addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    [_playView addSubview:playBtn];

    [playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_playView);
        make.centerY.equalTo(_playView);
        make.width.height.offset(100);
    }];
}

- (void)playAction {
    self.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:BH_Home_mp4]];
    AVPlayerViewController *playerVC = [[AVPlayerViewController alloc]init];
    playerVC.player = self.player;

    playerVC.view.frame = _playView.frame;
    [_playView addSubview:playerVC.view];
    [self addChildViewController:playerVC];
    
    [self.player play];
}

- (void)initView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[RefreshCollectionView alloc]initWithFrame:CGRectMake(0, kTopViewHeight, App_Frame_Width, App_Frame_Height-kBottomBarHeight-kTopViewHeight) collectionViewLayout:layout];
    self.collectionView.backgroundColor = Main_BackColor;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.refreshDelegate = self;
    self.collectionView.isRefresh = YES;
    [self.collectionView registerClass:[HomeCollectionViewCell class] forCellWithReuseIdentifier:cellId];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
    [self.view addSubview:self.collectionView];
}

- (void)chooseAddressAction:(UIButton *)sender {
    HomeAddressListViewController *next = [[HomeAddressListViewController alloc] init];
    next.chooseAddressBlock = ^(HomeAddressModel *addressModel) {
        self.cityName = [BHSettingUtil dataAndStringIsNull:addressModel.region_name]?@"全部":addressModel.region_name;
        self.cityId = addressModel.region_id;
        [_addressButton setTitle:self.cityName forState:UIControlStateNormal];
        [self requestPostBH_Exhibition_getExhibitionHallByCityId:YES PageCount:1];
    };
    [self pushViewController:next animated:YES];
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
- (void)collectionView:(UICollectionView *)collectionView Refresh:(BOOL)refresh PageCount:(NSInteger)pageCount {
    [self requestPostBH_Exhibition_getExhibitionHallByCityId:refresh PageCount:pageCount];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[HomeCollectionViewCell alloc]init];
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(kCellWidth, kCellHeight);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(20, 15, 20, 15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath];
        [header addSubview:self.playView];
        return header;
    }
    else {
        return nil;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(App_Frame_Width, kCycleViewHeight);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ShowViewController *next = [[ShowViewController alloc] init];
    HomeShowModel *model = self.dataArray[indexPath.item];
    next.Id = model.Id;
    next.cityId = [BHSettingUtil dataAndStringIsNull:self.cityId]?@"":self.cityId;
    next.hallTitle = [BHSettingUtil dataAndStringIsNull:model.title]?@"":model.title;
    [self pushViewController:next animated:YES];
}

#pragma mark -
- (void)_loadData:(id)response Refresh:(BOOL)refresh {
    if (refresh) [self.dataArray removeAllObjects];
    NSArray *arr = [NSArray yy_modelArrayWithClass:[HomeShowModel class] json:response];
    [self.dataArray addObjectsFromArray:arr];
    if (arr.count < 10) {
        [self.collectionView endRefreshingWithNoMoreData];
    }
    [self.collectionView reloadData];
}

#pragma mark - 接口
- (void)requestPostBH_Exhibition_getExhibitionHallByCityId:(BOOL)refresh PageCount:(NSInteger)pageCount {
    if (refresh) [[BHAlertUtil alertManager]showLoading:@""];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    [params setObject:@"" forKey:@"vague"];

    if (![BHSettingUtil dataAndStringIsNull:self.cityId]) {
        [params setObject:self.cityId forKey:@"city_id"];
    } else {
        [params setObject:@"383" forKey:@"city_id"];
    }
    [params setObject:[NSString stringWithFormat:@"%ld",pageCount] forKey:@"page"];
    [params setObject:@"10" forKey:@"pagesize"];

    [PPHTTPRequest requestPostBH_Exhibition_getExhibitionHallByCityId:^(id response, BOOL success) {
        if (self.dataArray.count == 0 && [response isKindOfClass:[NSString class]]) {
//            self.collectionView.placeholderShow(YES).prompt_title((NSString *)response).isButtonHidden(YES);
        }else self.collectionView.placeholderShow(NO);
        if (success && ![response isKindOfClass:[NSString class]]) {
            [self _loadData:response Refresh:refresh];
        }
        if (success && refresh == YES) {
            [self _loadData:response Refresh:refresh];
        }
        [[BHAlertUtil alertManager]hiddenLoading];
    } params:params];
}

//#pragma mark - 接口
//- (void)_loadData:(id)response Refresh:(BOOL)refresh {
//    if (refresh) [self.dataArray removeAllObjects];
//    NSArray *arr = [NSArray yy_modelArrayWithClass:[HomeShowListModel class] json:response];
//    [self.dataArray addObjectsFromArray:arr];
//    if (arr.count < 10) {
//        [self.collectionView endRefreshingWithNoMoreData];
//    }
//    [self.collectionView reloadData];
//}
//
//- (void)requestPostBH_Exhibition_getExhibitionList:(BOOL)refresh PageCount:(NSInteger)pageCount {
//    self.dataArray.count != 0 ?: [[BHAlertUtil alertManager]showLoadingView:self.view];
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
////    [params setObject:@"" forKey:@"vague"];
//    if (![BHSettingUtil dataAndStringIsNull:self.cityId]) {
//        [params setObject:self.cityId forKey:@"city_id"];
//    }
//    else {
//        self.cityName = @"全部";
//        [_addressButton setTitle:self.cityName forState:UIControlStateNormal];
//    }
////    [params setObject:@"" forKey:@"hall_id"];
////    [params setObject:@"" forKey:@"trade_id"];
////    [params setObject:@"" forKey:@"is_good"];
////    [params setObject:self.year forKey:@"year"];
////    [params setObject:[NSNumber numberWithInteger:self.page] forKey:@"month"];
//
//    [params setObject:[NSString stringWithFormat:@"%ld",(long)pageCount] forKey:@"page"];
//    [params setObject:@"10" forKey:@"pagesize"];
//
//    [PPHTTPRequest requestPostBH_Exhibition_getExhibitionList:^(id response, BOOL success) {
//        if (self.dataArray.count == 0 && [response isKindOfClass:[NSString class]]) {
//            self.collectionView.placeholderShow(YES).prompt_title(@"当前城市无展会");
//        }else self.collectionView.placeholderShow(NO);
//        if (success && ![response isKindOfClass:[NSString class]]) {
//            [self _loadData:response Refresh:refresh];
//        }
//        if (success && refresh == YES) {
//            [self _loadData:response Refresh:refresh];
//        }
//        [[BHAlertUtil alertManager]hiddenLoading];
//    } params:params];
//}

//轮播图
//- (void)_loadCycleData:(id)response {
////    [self.cycleDataArray removeAllObjects];
////    NSArray *arr = [NSArray yy_modelArrayWithClass:[HomeShowListModel class] json:response];
////    [self.cycleDataArray addObjectsFromArray:arr];
////    [self.cycleView reloadData];
//}

//- (void)requestPostBH_Ads_getSowing {
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    [PPHTTPRequest requestPostBH_Ads_getSowing:^(id response, BOOL success) {
////        if (self.dataArray.count == 0 && [response isKindOfClass:[NSString class]]) {
////            //            self.collectionView.placeholderShow(YES).prompt_title((NSString *)response).isButtonHidden(YES);
////        }else self.collectionView.placeholderShow(NO);
//        if (success && ![response isKindOfClass:[NSString class]]) {
//            [self _loadCycleData:response];
//        }
////        if (success && refresh == YES) {
////            [self _loadCycleData:response];
////        }
//        [[BHAlertUtil alertManager]hiddenLoading];
//    } params:params];
//}

//系统游客与展商数量统计系
- (void)_loadNumberData:(id)response {
    HomeNumberModel *model = [HomeNumberModel yy_modelWithJSON:response];
    self.registLabel.text = [NSString stringWithFormat:@"注册用户:%@位", model.reg_user_count];
    self.businessLabel.text = [NSString stringWithFormat:@"注册展商:%@位", model.reg_exhibition_count];
}

- (void)requestPostBH_User_getSysCount {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [PPHTTPRequest requestPostBH_User_getSysCount:^(id response, BOOL success) {
//        if (self.dataArray.count == 0 && [response isKindOfClass:[NSString class]]) {
//            //            self.collectionView.placeholderShow(YES).prompt_title((NSString *)response).isButtonHidden(YES);
//        }else self.collectionView.placeholderShow(NO);
        if (success && ![response isKindOfClass:[NSString class]]) {
            [self _loadNumberData:response];
        }
//        if (success && refresh == YES) {
//            [self _loadCycleData:response];
//        }
//        [[BHAlertUtil alertManager]hiddenLoading];
    } params:params];
}
#pragma mark ----------------------------定位---------------------------------
- (void)getCurrentAddress {
    //定位
    [self locService];
    [[BHAlertUtil alertManager] showLoadingView:self.view];
    [_locService startUserLocationService];
}
#pragma mark - 百度地图
- (BMKLocationService *)locService {
    if (_locService == nil) {
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8) {
            //由于IOS8中定位的授权机制改变 需要进行手动授权
            CLLocationManager  *locationManager = [[CLLocationManager alloc] init];
            //获取授权认证
            [locationManager requestAlwaysAuthorization];
        }
        //初始化BMKLocationService
        _locService = [[BMKLocationService alloc]init];
        _locService.delegate = self;
        _locService.desiredAccuracy = 100;
        //启动LocationService
        [_locService startUserLocationService];
        _geocodesearch = [[BMKGeoCodeSearch alloc]init];
        _geocodesearch.delegate = self;
    }
    return _locService;
}

- (void)didFailToLocateUserWithError:(NSError *)error {
    NSLog(@"error:%@",error);
}

//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //NSLog(@"heading is %@",userLocation.heading);
    NSLog(@"locService:%@,",_locService.userLocation.location);
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    //反geo检索
    NSLog(@"locService:%@,",_locService.userLocation.location);
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude, _locService.userLocation.location.coordinate.longitude};
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    
    BOOL flag1 = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    [_locService stopUserLocationService];
    if(flag1) {
        NSLog(@"反geo检索发送成功");
    } else {
        NSLog(@"反geo检索发送失败");
    }
    [[BHAlertUtil alertManager] hiddenLoading];
}


//接收反向地理编码结果
//反向地理编码
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    if (![BHSettingUtil dataAndStringIsNull:result]) {
        BMKAddressComponent *addressComponent = result.addressDetail;
        self.cityName = [BHSettingUtil dataAndStringIsNull:addressComponent.city]?@"全部":addressComponent.city;
        [_addressButton setTitle:self.cityName forState:UIControlStateNormal];

        [self requestPostBH_Region_getRegionId:addressComponent.city];
//        [self requestPostBH_Region_getRegionId:@"杭州"];

    }
}

- (void)requestPostBH_Region_getRegionId:(NSString *)cityName {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:cityName forKey:@"region_name"];//383杭州
    [PPHTTPRequest requestPostBH_Region_getRegionId:^(id response, BOOL success) {
        if (success) {
//            ZhanguanViewController *next = [[ZhanguanViewController alloc] init];
//            next.Id = response[@"region_id"];
//            [self.showInfoArray replaceObjectAtIndex:0 withObject:next.Id];
//            next.showInfoArray = self.showInfoArray;
//            [self pushViewController:next animated:YES];
            
            self.cityId = response[@"region_id"];
            
            [self.collectionView headerRefresh];

//            [self requestPostBH_Exhibition_getExhibitionList:YES PageCount:1];
        }
        
        else {
//            self.collectionView.placeholderShow(YES).isButtonHidden(YES).prompt_title(@"无法获取当前城市展会,换个城市看看");
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } params:params];
}

@end
